package com.tzstcl.framework.aspect;

import com.tzstcl.framework.datasource.DataSourceType;
import com.tzstcl.framework.datasource.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;


/**
 * 多数据源处理
 *
 */
@Aspect
@Order(-10)
@Component
public class DataSourceAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

//    @Pointcut("@annotation(com.tzstcl.framework.aop.DataSource)")
//    public void dsPointCut()
//    {
//
//    }
//
//    @Around("dsPointCut()")
//    public Object around(ProceedingJoinPoint point) throws Throwable
//    {
//        MethodSignature signature = (MethodSignature) point.getSignature();
//
//        Method method = signature.getMethod();
//
//        DataSource dataSource = method.getAnnotation(DataSource.class);
//
//        if (StringUtils.isNotNull(dataSource))
//        {
//            DynamicDataSourceContextHolder.setDateSoureType(dataSource.value().name());
//        }
//
//        try
//        {
//            return point.proceed();
//        }
//        finally
//        {
//            // 销毁数据源 在执行方法之后
//            DynamicDataSourceContextHolder.clearDateSoureType();
//        }
//    }

    @Before("@within(DataSource) || @annotation(DataSource)")
    public void changeDataSource(JoinPoint point) {
        // 获取方法上的注解
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        DataSource annotation = method.getAnnotation(DataSource.class);

        DataSourceType value;
        if (Objects.isNull(annotation)) {
            // 方法上没有注解, 获取类上的注解
            annotation = point.getTarget().getClass().getAnnotation(DataSource.class);
            if (Objects.isNull(annotation)) {
                return;
            }
        }
        // 获取注解值
        value = annotation.value();
//        System.out.println("切换数据源为："+value.name());
        // 切换数据源
        DynamicDataSourceContextHolder.setDateSoureType(value.name());
    }

    @After("@within(DataSource) || @annotation(DataSource)")
    public void clean() {
        // 清理数据源的标签
        DynamicDataSourceContextHolder.clearDateSoureType();
    }
}
